package com.lmt.ymcc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.lmt.ymcc.domain.AlipayInfo;
import com.lmt.ymcc.domain.PayOrder;
import com.lmt.ymcc.dto.CourseOrderPayparamDto;
import com.lmt.ymcc.dto.Order2PayParamDto;
import com.lmt.ymcc.mapper.PayOrderMapper;
import com.lmt.ymcc.service.IAlipayInfoService;
import com.lmt.ymcc.service.IPayOrderService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.lmt.ymcc.utils.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author AmazingXu
 * @since 2022-08-20
 */
@Service
@Slf4j
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {

    @Autowired
    private IAlipayInfoService alipayInfoService;

    @Override
    @Transactional
    public void savePayOrder(Order2PayParamDto order2PayParamDto) {
        String orderNo = order2PayParamDto.getOrderNo();
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no", orderNo);
        PayOrder payOrder = selectOne(wrapper);
        if(payOrder == null){
            payOrder = new PayOrder();
            BeanUtils.copyProperties(order2PayParamDto,payOrder);
            payOrder.setCreateTime(new Date());
            payOrder.setPayStatus(PayOrder.STATE_WAIT_PAY);
            insert(payOrder);
        }
    }

    @Override
    public String apply(CourseOrderPayparamDto dto) {
        PayOrder payOrder = checkPayOrder(dto.getOrderNo());
        AssertUtil.isNotNull(payOrder, "支付单不存在！！");
        // 判断支付单的状态
        boolean isWaitPay = payOrder.getPayStatus() == PayOrder.STATE_WAIT_PAY;
        AssertUtil.isTrue(isWaitPay, "支付单状态不合规");
        // 判断用户选择的支付方式，调用支付方法
        int payType = payOrder.getPayType().intValue();
        if (payType== 1) {
            return alipay(payOrder, dto);
        }else if (payType == 2) {
            // 调用微信支付方法
        }
        return null;
    }

    @Override
    public PayOrder checkPayOrder(String orderNo) {
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        return selectOne(wrapper);
    }

    public String alipay(PayOrder payOrder, CourseOrderPayparamDto dto) {
        // 设置参数
        AlipayInfo alipayInfo = alipayInfoService.selectList(null).get(0);
        Factory.setOptions(getOptions(alipayInfo));
        try {
            // 网页支付
            AlipayTradePagePayResponse response = Factory.Payment.Page().pay(
                    payOrder.getSubject(),
                    payOrder.getOrderNo(),
                    payOrder.getAmount().toString(),
                    StringUtils.isEmpty(dto.getCallUrl()) ? alipayInfo.getReturnUrl():dto.getCallUrl()
            );
            // 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println(response.getBody());
                return response.getBody();
            } else {
                System.err.println("调用失败：" + response);
            }
        } catch (Exception e) {
            System.err.println("调用异常：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return null;
    }


    private Config getOptions(AlipayInfo alipayInfo) {
        Config config = new Config();
        config.protocol = alipayInfo.getProtocol();
        config.gatewayHost = alipayInfo.getGatewayHost();
        config.signType = alipayInfo.getSignType();
        config.appId = alipayInfo.getAppId();
        config.merchantPrivateKey = alipayInfo.getMerchantPrivateKey();
        config.alipayPublicKey = alipayInfo.getAlipayPublicKey();
        config.notifyUrl = alipayInfo.getNotifyUrl();
        return config;
    }

    // 取消支付
    @Override
    @Transactional
    public void cancelPayOrderByPayTimeOut(String orderNo) {
        PayOrder payOrder = checkPayOrder(orderNo);
        if(payOrder == null){
            return;
        }
        if(payOrder.getPayStatus() != PayOrder.STATE_WAIT_PAY){
            return;
        }
        // 取消支付单
        payOrder.setPayStatus(PayOrder.STATE_CANCEL);
        payOrder.setUpdateTime(new Date());
        updateById(payOrder);
        // 调用支付宝关闭交易
        try {
            AlipayTradeCloseResponse close = Factory.Payment.Common().close(orderNo);
            log.info("调用支付宝关闭交易：{}", JSON.toJSONString(close));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
